package db

import (
	"fmt"
	"net/url"
	"strings"
)

const mysqlDSNFormat = "%s:%s@tcp(%s)/%s?charset=%s&parseTime=True&interpolateParams=true&timeout=30s&readTimeout=%s&writeTimeout=%s"
const pgDSNFormat = "postgres://%s:%s@%s/%s?connect_timeout=30&search_path=%s&sslmode=%s"

func ParseMysqlDSN(c Config, o Options) (primary string, secondary []string) {
	getDSN := func(a string) string {
		dsn := fmt.Sprintf(mysqlDSNFormat, c.Username, c.Password, a, c.DBName, c.Charset, o.ReadTimeout, o.WriteTimeout)
		return dsn
	}

	primary = getDSN(c.Address)

	for _, a := range c.Secondary {
		a = strings.TrimSpace(a)

		secondary = append(secondary, getDSN(a))
	}

	return
}

func ParsePgDSN(c Config, o Options) (primary string, secondary []string) {
	if c.SearchPath == "" {
		c.SearchPath = "public"
	}

	sm := url.QueryEscape(o.SSLMode)
	sp := url.QueryEscape(c.SearchPath)

	getDSN := func(a string) string {
		dsn := fmt.Sprintf(pgDSNFormat, c.Username, c.Password, a, c.DBName, sp, sm)
		return dsn
	}

	primary = getDSN(c.Address)

	for _, a := range c.Secondary {
		a = strings.TrimSpace(a)

		if a == "" {
			continue
		}
		secondary = append(secondary, getDSN(a))
	}
	return
}
